package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
	"strconv"
	"time"
)

type NovelController struct {
	beego.Controller
}

func (c *NovelController) Add() {

	name := c.GetString("name")
	user := c.GetString("user")
	img := c.GetString("img")
	types := c.GetString("types")
	address := c.GetString("address")

	var nov = models.Nov{
		Name:    name,
		User:    user,
		Img:     img,
		Types:   types,
		Address: address,
	}
	if name == "" || user == "" {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "小说名称，作者是必填项",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Create(&nov).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *NovelController) List() {
	user := c.GetString("name")
	where := map[string]string{}
	if user != "" {
		where["user"] = user
	}

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	var count int64
	models.DB.Model(&models.Nov{}).Count(&count)
	offset := (page - 1) * size
	var nov []models.Nov
	pageDate := make(map[string]interface{})
	key := "nov-" + strconv.Itoa(page)
	val, err := models.Rds.Get(key).Result()
	if err != nil {
		err = models.DB.Where(where).Offset(offset).Limit(size).Find(&nov).Error
		if err != nil {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageDate["count"] = count
		pageDate["nov"] = nov
		xx, _ := json.Marshal(&pageDate)
		value := string(xx)
		models.Rds.Set(key, value, time.Second*5)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-mysql",
			Data: pageDate,
		}
		c.ServeJSON()

	} else {
		json.Unmarshal([]byte(val), &pageDate)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: pageDate,
		}
		c.ServeJSON()
	}

}
func (c *NovelController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 0,
			Msg:  "获取文件失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)

}
